package cn.aion.crawlers;

import cn.aion.dao.ProjectVideoDAO;
import cn.aion.dao.VideoDataDAO;
import cn.aion.model.ProjectVideo;
import cn.aion.model.ToutiaoVideo;
import cn.aion.model.VideoData;
import cn.aion.util.Helper;
import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 秒拍扫描规则：http://www.miaopai.com/show/-p23l24AaDXMjnGZ98AuMw__.htm
 * Created by 虚空之翼 on 2016/12/14.
 */
@Crawler(name = "miaopai", useUnrepeated = false)
public class Miaopai extends BaseSeimiCrawler {
    @Autowired
    private ProjectVideoDAO projectVideoDAO;
    @Autowired
    private VideoDataDAO videoDataDAO;

    @Override
    public String[] startUrls() {
        return new String[]{"http://www.van-cool.com/admin/base/scan"};
    }

    @Override
    public void start(Response response) {
        main();
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void main() {
        logger.info("开启秒拍扫描任务");
        try {
            List<ProjectVideo> list = projectVideoDAO.getVideoAll();
            for (ProjectVideo video : list) {
                String url = video.getMiaopaiUrl();
                if (url != null && !url.isEmpty()) {
                    logger.info("扫描地址：{}", url);
                    push(Request.build(url, "fetchData"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchData(Response response){
        JXDocument doc = response.document();

        // 根据URL获取视频ID
        ProjectVideo projectVideo = projectVideoDAO.selectOneByMiaopai(response.getUrl());

        try {
            String playStr = StringUtils.join(doc.sel("//p[@class='personalDataT']/span[@class='red']/text()"),"");
//            String commentStr = StringUtils.join(doc.sel("//div[@class='talk']/div/a[position()=2]/text()"),"");
//            playStr = playStr.replace("&nbsp;&nbsp;&nbsp;", " ");
//            String[] playStrArr = playStr.split(" ");
//            logger.info("{}| {},{},{}", playStr,playStrArr[0], playStrArr[1]);
            System.out.println(playStr);
            float play = Float.parseFloat(playStr.replace("万", "").replace("观看", "").replace(",", ""));
            if (playStr.contains("万")) {
                play *= 10000;
            }
//            commentStr = commentStr.replace("评论","").replaceAll(" ", "");
            logger.info("{} | 播放总数:{}，评论:{}", projectVideo.getTitle(), play, "commentStr");

            // 计算当日的递增数量
            VideoData preData = videoDataDAO.selectOnePrevious(projectVideo.getId(), 8);
            Integer playCount = (int)play;
            Integer addCount = playCount;
            if (preData != null) {
                addCount = playCount - preData.getPlayCount();
            }

            // 如果当天已经抓取过数据就更新数据
            VideoData videoData = videoDataDAO.selectOneToday(projectVideo.getId(), 8);
            if (videoData != null) {
                if (playCount != 0) {
                    videoData.setPlayCount(playCount);
                    videoData.setPlayAdd(addCount);
//                    videoData.setComments(Integer.parseInt(commentStr));
                    videoDataDAO.update(videoData);
                }
            } else {
                VideoData newData = new VideoData();
                newData.setPlayCount(playCount);
                newData.setPlayAdd(addCount);
//                newData.setComments(Integer.parseInt(commentStr));
                newData.setVideoId(projectVideo.getId());
                newData.setSrcType(8);
                videoDataDAO.save(newData);
            }
            // 更新总数据
            if (playCount != 0) {
                projectVideoDAO.updateMiaopaiVideoCount(projectVideo.getId(), playCount);
                projectVideoDAO.updateTotal(projectVideo.getId());
                projectVideoDAO.updateApplyTotal(projectVideo.getProjectId(), projectVideo.getAnchorId(), Helper.getVideoTotal(projectVideo));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
